package pl.softech.oldchart;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;

public class LineGraphView implements IGraphView {

	@Override
	public void drawGraph(Graphics2D g2, IGraph2DModel model, IGraphToolKit toolKit) {
		
		double pointRadius = toolKit.getCoordinatePointRadius();
		
		Collection<Point2D> points = model.getPoints();
		Color graphColor = model.getGraphColor(); 
		Point2D[] tab = new Point2D[0];
		tab = points.toArray(tab);
		Arrays.sort(tab, new Comparator<Point2D>() {

			@Override
			public int compare(Point2D o1, Point2D o2) {
				
				double diff = o1.getX() - o2.getX();
				if(diff ==  0) return 0;
				
				return ((diff > 0) ? 1 : -1);
			}
			
		});
		
		Point2D last = null;
		boolean drawModelCoordinates = toolKit.getDrawModelCoordinates();
		for(int i = 0; i < tab.length; i++) {
			
			Color color = g2.getColor();
			g2.setColor(graphColor);
			
			Point2D p = toolKit.convertPointFromModelToView(tab[i]);
			
			if(model.drawCoordinates() && drawModelCoordinates) {
				
				Ellipse2D ellipse = new Ellipse2D.Double(p.getX() - pointRadius / 2,
						p.getY() - pointRadius / 2, pointRadius, pointRadius);
			
				
				g2.fill(ellipse);
			
			}
			
			if(last != null) {
				Line2D line = new Line2D.Double(last, p);
				g2.draw(line);
			}
			last = p;
			g2.setColor(color);
			
		}

		
	}

	@Override
	public String toString() {
		return "Line graph";
	}
	
}
